package pl.smath.js.client;

import pl.smath.expression.model.Term;
import pl.smath.expression.parser.ExpressionParser;
import pl.smath.expression.parser.ExpressionParserException;
import pl.smath.renderer.renderer.TermRendererException;
import pl.smath.renderer.renderer.TermWidgetFactory;
import pl.smath.renderer.utils.InteractionManager;

import com.google.gwt.core.client.JavaScriptObject;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.RootPanel;

public class SmathController {

	private JavaScriptObject jsObject;
	private InteractionManager interactionManager;
	
	public SmathController(String id, String expression){
		jsObject = JavaScriptObject.createFunction();
		initJavaScriptObject(jsObject);

		try {
			FlowPanel main = new FlowPanel();
			RootPanel.get(id).add(main);
			ExpressionParser parser = new ExpressionParser();
			TermWidgetFactory factory = new TermWidgetFactory();
			factory.setFontHeight("22px");
			interactionManager = new InteractionManager(main);

			Term term;
			if (expression.indexOf("<") == -1  ||  expression.indexOf(">") == -1)
				term = parser.parseText(expression);
			else
				term = parser.parseMathML(expression);
			factory.createWidget(term, interactionManager);
			interactionManager.process();
		} catch (ExpressionParserException e) {
		} catch (TermRendererException e) {
		} catch (Exception e){
		}
	}
	
	public native void initJavaScriptObject(JavaScriptObject jsObject)/*-{
		var instance = this;
		jsObject.getGapTextAt = function(index){
			return instance.@pl.smath.js.client.SmathController::getGapTextAt(I)(index);
		}
		jsObject.setGapTextAt = function(index, text){
			instance.@pl.smath.js.client.SmathController::setGapTextAt(ILjava/lang/String;)(index, text);
		}
		jsObject.getGapsCount = function(){
			return instance.@pl.smath.js.client.SmathController::getGapsCount()();
		}
		jsObject.getGapElementAt = function(index){
			return instance.@pl.smath.js.client.SmathController::getGapElementAt(I)(index);
		}
	}-*/;
	
	public JavaScriptObject getJavaScriptObject(){
		return jsObject;
	}

	public String getGapTextAt(int index){
		return interactionManager.getGapAt(index).getText();
	}
	
	public void setGapTextAt(int index, String text){
		interactionManager.getGapAt(index).setText(text);
	}
	public int getGapsCount(){
		return interactionManager.getGapsCount();
	}
	public Element getGapElementAt(int index){
		return interactionManager.getGapAt(index).getElement();
	}
}
